package com.bank.frame;

import com.bank.dao.AccountDAO;
import com.bank.dao.RecordDAO;
import com.bank.utils.SystemConstants;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Date;

/**
 * 用户查看自己的银行卡账号
 */
public class UserAccountTablePanel extends JInternalFrame {

    public UserAccountTablePanel() {
        super("账户查询", true, true, true, true);
        this.setSize(SystemConstants.FRAME_WIDTH, SystemConstants.FRAME_HEIGHT);
        JTable table = new JTable() {
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        refresh(table, MainFrame.user.getUsername());

        JPanel topPanel = new JPanel();
        JButton recordBtn = new JButton("交易记录");
        topPanel.add(recordBtn);
        JButton inBtn = new JButton("存款");
        topPanel.add(inBtn);
        JButton outBtn = new JButton("取款");
        topPanel.add(outBtn);
        JButton transferBtn = new JButton("转账");
        topPanel.add(transferBtn);
        // 这个密码是银行卡的取款密码，不是登录密码
        JButton editBtn = new JButton("修改支付密码");
        topPanel.add(editBtn);

        JPanel panel = new JPanel(new BorderLayout());
        panel.setSize(SystemConstants.FRAME_WIDTH, SystemConstants.FRAME_HEIGHT);
        // 查看交易记录
        recordBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int rowNum = table.getSelectedRow();
                if (rowNum <= -1) {
                    return;
                }
                String card = table.getValueAt(rowNum, 0).toString();
                com.bank.frame.UserPanel.setContent(new RecordTablePanel(card, MainFrame.user.getUsername()));
            }
        });
        //  修改支付密码
        editBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int rowNum = table.getSelectedRow();
                if (rowNum <= -1) {
                    return;
                }
                if (SystemConstants.ACCOUNT_STATUS_DISABLE.equals(table.getValueAt(rowNum, 7).toString())) {
                    JOptionPane.showMessageDialog(editBtn.getParent(), "该账户已注销", "系统提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                // 带输入框的弹窗，点击取消按钮input为null
                String input = JOptionPane.showInputDialog(editBtn.getParent(), "请输入原始密码", "系统提示",
                        JOptionPane.WARNING_MESSAGE);
                if (input == null) {
                    return;
                }
                String card = table.getValueAt(rowNum, 0).toString();
                Object[] account = AccountDAO.findByCard(card);
                if (!input.equals(account[8])) {
                    JOptionPane.showMessageDialog(editBtn.getParent(), "原始密码错误", "系统提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                // 获取新密码
                input = JOptionPane.showInputDialog(transferBtn.getParent(), "请输入新密码", "系统提示", JOptionPane.WARNING_MESSAGE);
                if (input == null || input.trim().length() != 6) {
                    JOptionPane.showMessageDialog(editBtn.getParent(), "密码长度必须是6位", "系统提示",
                            JOptionPane.WARNING_MESSAGE);
                    return;
                }
                AccountDAO.updatePassword(card, input);
            }
        });
        //  存款
        inBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int rowNum = table.getSelectedRow();
                if (rowNum <= -1) {
                    return;
                }
                if (SystemConstants.ACCOUNT_STATUS_DISABLE.equals(table.getValueAt(rowNum, 7).toString())) {
                    //判断是否注销
                    JOptionPane.showMessageDialog(editBtn.getParent(), "该账户已注销", "系统提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                String card = table.getValueAt(rowNum, 0).toString();
                String input = JOptionPane.showInputDialog(inBtn.getParent(), "请输入存款金额", "系统提示",
                        JOptionPane.WARNING_MESSAGE);
                if (input == null) {
                    return;
                }
                double amount;//定义用来存储输入的存款金额
                try {
                    amount = Double.parseDouble(input);
                } catch (Exception ex) {
                    // 如果输入的是字符串会报异常
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(inBtn.getParent(), "金额无效", "系统提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                if (amount <= 0) {
                    JOptionPane.showMessageDialog(inBtn.getParent(), "金额无效", "系统提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }

                Object[] account = AccountDAO.findByCard(card);
                // 验证二类卡限额  ||  二类卡限制每日 （存款 + 转入） 金额不大于 1w 元
                if (SystemConstants.ACCOUNT_TYPE_II.equals(account[6])) {
                    double today = RecordDAO.getTodayAmount(account[0].toString(), "in");//  得到今天的转入金额
                    if (today + amount > 10000) {
                        JOptionPane.showMessageDialog(inBtn.getParent(), "Ⅱ类卡单日转入(含存款)限额1万,当前已交易" + today, "系统提示",
                                JOptionPane.WARNING_MESSAGE);
                        return;
                    }
                }
                // 增加余额
                account[4] = (double) account[4] + amount;
                AccountDAO.update(card, account);

                // 记录交易记录："交易编号", "卡号", "交易时间", "交易类型", "交易金额", "余额",
                // "对方姓名", "对方账户", "交易备注"
                Object[] record = new Object[]{System.currentTimeMillis(), account[0],
                        SystemConstants.DATE_FORMAT.format(new Date()), SystemConstants.TRADE_TYPE_SAVING, "+" + amount,
                        account[4], "", "", "ATM存入"};// 存款，所以对方姓名和对方账户为null
                RecordDAO.add(record);
                refresh(table, table.getValueAt(rowNum, 1).toString());

            }
        });
        //  取款
        outBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int rowNum = table.getSelectedRow();
                if (rowNum <= -1) {
                    return;
                }
                if (SystemConstants.ACCOUNT_STATUS_DISABLE.equals(table.getValueAt(rowNum, 7).toString())) {
                    //  判断是否注销
                    JOptionPane.showMessageDialog(editBtn.getParent(), "该账户已注销", "系统提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                // 卡号
                String card = table.getValueAt(rowNum, 0).toString();
                // 取款需要密码
                String input = JOptionPane.showInputDialog(outBtn.getParent(), "请用户输入取款密码", "系统提示",
                        JOptionPane.WARNING_MESSAGE);
                if (input == null) {
                    return;
                }
                Object[] account = AccountDAO.findByCard(card);
                if (!input.equals(account[8])) {
                    //  如果密码不正确报错
                    JOptionPane.showMessageDialog(outBtn.getParent(), "密码错误", "系统提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                //  密码正确继续向下指向
                input = JOptionPane.showInputDialog(outBtn.getParent(), "请输入取款金额", "系统提示", JOptionPane.WARNING_MESSAGE);
                if (input == null) {
                    return;
                }
                double amount;
                try {
                    amount = Double.parseDouble(input);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    JOptionPane.showMessageDialog(outBtn.getParent(), "金额无效", "系统提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                if (amount <= 0) {
                    JOptionPane.showMessageDialog(outBtn.getParent(), "金额无效", "系统提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                if ((double) account[4] < amount) {
                    JOptionPane.showMessageDialog(outBtn.getParent(), "余额不足", "系统提示", JOptionPane.WARNING_MESSAGE);
                    return;
                }
                // 验证二类卡限额
                if (SystemConstants.ACCOUNT_TYPE_II.equals(account[6])) {
                    double today = RecordDAO.getTodayAmount(account[0].toString(), "out");
                    if (today - amount < -10000) {
                        JOptionPane.showMessageDialog(inBtn.getParent(), "Ⅱ类卡单日转出(含取款)限额1万,当前已交易" + today, "系统提示",
                                JOptionPane.WARNING_MESSAGE);
                        return;
                    }
                }
                // 减掉余额，并记录
                account[4] = (double) account[4] - amount;
                AccountDAO.update(card, account);
                Object[] record = new Object[]{System.currentTimeMillis(), account[0],
                        SystemConstants.DATE_FORMAT.format(new Date()), SystemConstants.TRADE_TYPE_WITHDRAW,
                        "-" + amount, account[4], "", "", "ATM取款"};
                RecordDAO.add(record);
                refresh(table, table.getValueAt(rowNum, 1).toString());
            }
        });
        //  转账
        transferBtn.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int rowNum = table.getSelectedRow();
                if (rowNum <= -1) {
                    com.bank.frame.UserPanel.setContent(new TransferPanel(null));
                } else {
                    if (SystemConstants.ACCOUNT_STATUS_DISABLE.equals(table.getValueAt(rowNum, 7).toString())) {
                        JOptionPane.showMessageDialog(editBtn.getParent(), "该账户已注销", "系统提示",
                                JOptionPane.WARNING_MESSAGE);
                        return;
                    }
                    // 如果选中了一张卡，打开新页面默认选中这张卡
                    String card = table.getValueAt(rowNum, 0).toString();
                    com.bank.frame.UserPanel.setContent(new TransferPanel(card));
                }

            }
        });

        // 把 表头 添加到容器顶部（使用普通的中间容器添加表格时，表头 和 内容 需要分开添加）
        panel.add(table.getTableHeader(), BorderLayout.NORTH);
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // 单选
        // 把 表格内容 添加到容器中心
        this.add(topPanel, BorderLayout.NORTH);
        panel.add(table, BorderLayout.CENTER);
        this.add(panel, BorderLayout.CENTER);
        // 显示内部窗口
        this.setVisible(true);
    }

    /**
     * 封装一下刷新表格的方法
     */
    public void refresh(JTable table, String text) {
        // 根据身份证号查询所有账号
        TableModel tableModel = new DefaultTableModel(AccountDAO.search(1, text), AccountDAO.columnNames);
        table.setModel(tableModel);
        // 隐藏列开始
        TableColumnModel tcm = table.getColumnModel();
        TableColumn tc = tcm.getColumn(8);
        tc.setMaxWidth(0);
        tc.setPreferredWidth(0);
        tc.setWidth(0);
        tc.setMinWidth(0);
        tcm = table.getTableHeader().getColumnModel();
        tc = tcm.getColumn(8);
        tc.setMaxWidth(0);
        tc.setPreferredWidth(0);
        tc.setWidth(0);
        tc.setMinWidth(0);
        // 隐藏列结束
    }
}
